package com.wasu.netutils.live;

import static com.wasu.constant.HttpDomainKt.SYSTEM_CATEGORY_4K_IPDVB_HUIFANG;
import static com.wasu.constant.HttpDomainKt.SYSTEM_CATEGORY_4K_IPDVB_KANBA;
import static com.wasu.constant.HttpDomainKt.SYSTEM_CATEGORY_4K_IPDVB_LIVE;
import static com.wasu.constant.HttpDomainKt.SYSTEM_CATEGORY_4K_IPDVB_QIUSUO;
import static com.wasu.sdk_ott.provider.WasuSdkUriMatcherKt.FAVORITES_DB_PATH;
import static com.wasu.sdk_ott.provider.WasuSdkUriMatcherKt.PATH_WASU_SDK_IPLIVE_CHANNEL;
import static com.wasu.sdk_ott.provider.WasuSdkUriMatcherKt.PATH_WASU_SDK_IPLIVE_CHANNEL_GROUP;
import static com.wasu.sdk_ott.provider.WasuSdkUriMatcherKt.PATH_WASU_SDK_IPLIVE_CHANNEL_PURCHASED;
import static com.wasu.sdk_ott.provider.WasuSdkUriMatcherKt.PATH_WASU_SDK_IPLIVE_CHANNEL_TIMESHIFT;
import static com.wasu.sdk_ott.provider.WasuSdkUriMatcherKt.PATH_WASU_SDK_IPLIVE_PROGRAM;
import static com.wasu.sdk_ott.provider.WasuSdkUriMatcherKt.RESULT_WASU_SDK_COLLECT;
import static com.wasu.sdk_ott.provider.WasuSdkUriMatcherKt.RESULT_WASU_SDK_IPLIVE;
import static com.wasu.sdk_ott.provider.WasuSdkUriMatcherKt.WASU_SDK_PROVIDER_URI;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;
import com.wasu.UILApplication;
import com.wasu.constant.Config;
import com.wasu.constant.HttpDomainKt;
import com.wasu.doicommon.constant.AppConstant;
import com.wasu.doicommon.util.AppCheckUtils;
import com.wasu.doicommon.util.NetworkUtils;
import com.wasu.doicommon.util.SharedPreferenceHelper;
import com.wasu.entity.DicInfo;
import com.wasu.entity.DicList;
import com.wasu.entity.live.WasuBouChInfor;
import com.wasu.entity.live.WasuBouInfor;
import com.wasu.entity.live.WasuChInfor;
import com.wasu.entity.live.WasuEdit;
import com.wasu.entity.live.WasuEditChRelated;
import com.wasu.entity.live.WasuEditInfor;
import com.wasu.netutils.DataSource;
import com.wasu.sdk_ott.service.LiveSortHelper;
import com.wasu.utils.TimeUtil;

import java.lang.ref.WeakReference;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.regex.Pattern;

/**
 * <p>------------------------------------------------------
 * <p>Copyright (C) 2020 wasu company, All rights reserved.
 * <p>------------------------------------------------------
 * <p> 以cp的方式请求IP直播管理系统并封装bean
 * <p>
 *
 * @author Created by zhangmz
 * @date on 2023/8/25
 */
public class DataSourceLive extends DataSource {

    private final static String TAG = HttpDomainKt.TAG;

    private final Pattern p = Pattern.compile("[0-9]*$");

    private static final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
    private static final SimpleDateFormat format2 = new SimpleDateFormat("MM月dd日", Locale.CHINA);

    private static volatile WeakReference<DataSourceLive> instance = null;

    public static synchronized DataSourceLive getInstance(){
        if (instance == null || instance.get() == null){
            synchronized (DataSourceLive.class){
                if (instance == null || instance.get() == null){
                    DataSourceLive dataSourceLive = new DataSourceLive();
                    instance = new WeakReference<>(dataSourceLive);
                }
            }
        }
        return instance.get();
    }

    /**
     * 链接的是 wasu_sdk module下的cp
     */
    private final Uri BASE_URI = Uri.parse("content://" + WASU_SDK_PROVIDER_URI);

    private Uri createUri(String uriPath){
        return BASE_URI.buildUpon().appendPath(uriPath).build();
    }

    /**
     * 查询某个分组下所有频道
     */
    public List<WasuBouInfor> queryChannelGroup(Context context){
        return queryChannelGroup(context, "1");
    }
    public List<WasuBouInfor> queryChannelGroup(Context context, String isZip){
        return queryChannelGroup(context, LiveCacheStrategy.FIRST_CACHE, isZip);
    }
    public List<WasuBouInfor> queryChannelGroup(Context context, LiveCacheStrategy strategy, String isZip){
        return queryChannelGroup(context, strategy, "", isZip);
    }
    public List<WasuBouInfor> queryChannelGroup(Context context, LiveCacheStrategy strategy, String bIds, String isZip){
        Uri uri = createUri(PATH_WASU_SDK_IPLIVE_CHANNEL_GROUP);
        String[] param = new String[]{createStrategy(strategy), bIds, isZip, ""};
        WasuBouChInfor wasuBouChInfor = createRequest(context, uri, param, RESULT_WASU_SDK_IPLIVE, WasuBouChInfor.class);
        // 直播的分组频道策略是缓存优先，如果缓存中的数据createRequestbList是空的，则修改策略为网络查询，重新查询接口获取新数据，并保存缓存
        if (wasuBouChInfor == null || wasuBouChInfor.getbList() == null || wasuBouChInfor.getbList().size() == 0){
            String[] paramNet = new String[]{createStrategy(LiveCacheStrategy.NETWORK), bIds, isZip, ""};
            wasuBouChInfor = createRequest(context, uri, paramNet, RESULT_WASU_SDK_IPLIVE, WasuBouChInfor.class);
        }
        // 如果第二次修改策略为网络查询后还是bList为空，那就是服务端真的没数据，不再查询
        if (wasuBouChInfor == null || wasuBouChInfor.getbList() == null || wasuBouChInfor.getbList().size() == 0){
            return new ArrayList<>();
        }
        wasuBouChInfor = LiveSortHelper.INSTANCE.sortChannelGroup(wasuBouChInfor);
        return wasuBouChInfor.getbList();
    }

    /**
     * 看吧分组频道
     */
    public WasuBouChInfor queryChannelGroupKanBa(Context context){
        return queryChannelGroupOther(context, SYSTEM_CATEGORY_4K_IPDVB_KANBA, "1");
    }
    public WasuBouChInfor queryChannelGroupKanBa(Context context, String isZip){
        return queryChannelGroupOther(context, SYSTEM_CATEGORY_4K_IPDVB_KANBA, isZip);
    }
    /**
     * 回放分组频道
     */
    public WasuBouChInfor queryChannelGroupHuiFang(Context context){
        return queryChannelGroupOther(context, SYSTEM_CATEGORY_4K_IPDVB_HUIFANG, "1");
    }
    public WasuBouChInfor queryChannelGroupHuiFang(Context context, String isZip){
        return queryChannelGroupOther(context, SYSTEM_CATEGORY_4K_IPDVB_HUIFANG, isZip);
    }
    /**
     * 求索分组频道
     */
    public WasuBouChInfor queryChannelGroupQiuSuo(Context context){
        return queryChannelGroupOther(context, SYSTEM_CATEGORY_4K_IPDVB_QIUSUO, "1");
    }
    public WasuBouChInfor queryChannelGroupQiuSuo(Context context, String isZip){
        return queryChannelGroupOther(context, SYSTEM_CATEGORY_4K_IPDVB_QIUSUO, isZip);
    }

    private WasuBouChInfor queryChannelGroupOther(Context context, String category, String isZip){
        Uri uri = createUri(PATH_WASU_SDK_IPLIVE_CHANNEL_GROUP);
        String[] param = new String[]{createStrategy(LiveCacheStrategy.ONLY_NETWORK), "", isZip, category};
        WasuBouChInfor wasuBouChInfor = createRequest(context, uri, param, RESULT_WASU_SDK_IPLIVE, WasuBouChInfor.class);
        if (wasuBouChInfor == null){ wasuBouChInfor = new WasuBouChInfor(); }
        return wasuBouChInfor;
    }

    /**
     * 查询时移频道列表
     * @param context
     * @return
     */
    public List<WasuBouInfor> queryChannelTimeShift(Context context){
        return queryChannelTimeShift(context, "1");
    }
    public List<WasuBouInfor> queryChannelTimeShift(Context context, String isZip){
        Uri uri = createUri(PATH_WASU_SDK_IPLIVE_CHANNEL_TIMESHIFT);
        String[] param = new String[]{TextUtils.isEmpty(isZip) ? "1" : isZip};
        WasuBouChInfor wasuBouChInfor = createRequest(context, uri, param, RESULT_WASU_SDK_IPLIVE, WasuBouChInfor.class);
        if (wasuBouChInfor == null || wasuBouChInfor.getbList() == null || wasuBouChInfor.getbList().size() == 0){
            return new ArrayList<>();
        }
        return wasuBouChInfor.getbList();
    }

    /**
     * 查询收藏的频道列表
     */
    public WasuBouInfor queryCollectChannelGroup(Context context, String sortBy){
        Uri uri = createUri(FAVORITES_DB_PATH);
        String[] param = new String[]{sortBy};
        return createRequest(context, uri, param, RESULT_WASU_SDK_COLLECT, WasuBouInfor.class);
    }

    /**
     * 查询单个频道详情
     */
    public List<WasuChInfor> queryChannel(Context context, String channelId){
        if (NetworkUtils.isConnected()){
            return queryChannel(context, null, channelId, null);
        }else {
            return queryChannelFromCache(context, channelId);
        }
    }
    public List<WasuChInfor> queryChannel(Context context, String channelId, String channelName){
        if (NetworkUtils.isConnected()){
            return queryChannel(context, null, channelId, channelName);
        }else {
            return queryChannelFromCache(context, channelId);
        }
    }
    public List<WasuChInfor> queryChannelKanBa(Context context, String channelId){
        return queryChannel(context, SYSTEM_CATEGORY_4K_IPDVB_KANBA, channelId, "");
    }
    public List<WasuChInfor> queryChannelHuiFang(Context context, String channelId){
        return queryChannel(context, SYSTEM_CATEGORY_4K_IPDVB_HUIFANG, channelId, "");
    }
    public List<WasuChInfor> queryChannelQiuSuo(Context context, String channelId){
        return queryChannel(context, SYSTEM_CATEGORY_4K_IPDVB_QIUSUO, channelId, "");
    }
    public List<WasuChInfor> queryChannel(Context context, String category, String channelId, String channelName){
        Uri uri = createUri(PATH_WASU_SDK_IPLIVE_CHANNEL);
        String[] param = new String[]{category, channelId, channelName};
        WasuBouInfor wasuBouInfor = createRequest(context, uri, param, RESULT_WASU_SDK_IPLIVE, WasuBouInfor.class);
        return wasuBouInfor == null ? Collections.emptyList() : wasuBouInfor.getChList();
    }

    /**
     * 查询单个频道信息，没有网络时，去分组频道缓存做循环匹配
     * @param chIds 频道id，多个以英文,分隔
     */
    private List<WasuChInfor> queryChannelFromCache(Context context, String chIds){
        List<WasuBouInfor> bouInforList = queryChannelGroup(context);
        List<WasuChInfor> channelResultList = new ArrayList<>();
        String[] channelIds = chIds.split(",");
        for (String channelId : channelIds) {
            for (int j = 0; j < bouInforList.size(); j++) {
                WasuBouInfor wasuBouInfor = bouInforList.get(j);
                List<WasuChInfor> wasuChInforList = wasuBouInfor.getChList();
                for (int a = 0; a < wasuChInforList.size(); a++) {
                    WasuChInfor wasuChInfor = wasuChInforList.get(a);
                    if (wasuChInfor.getChId().equals(channelId)) {
                        channelResultList.add(wasuChInfor);
                        break;
                    }
                }
            }
        }
        return channelResultList;
    }

    /**
     * 查询多频道节目单列表
     */
    public List<WasuEditChRelated> queryAllTodayProgram(Context context){
        return queryAllTodayProgram(context, LiveCacheStrategy.FIRST_CACHE, "1", "1", "1", false);
    }
    public List<WasuEditChRelated> queryAllTodayProgram(Context context, String isZip){
        return queryAllTodayProgram(context, LiveCacheStrategy.FIRST_CACHE, "1", "1", isZip, false);
    }
    public List<WasuEditChRelated> queryAllTodayProgram(Context context, LiveCacheStrategy strategy, String type, String getType){
        return queryAllTodayProgram(context, strategy, type, getType, "1", false);
    }

    /**
     * @param isZip 1:压缩包；0:json格式String，服务端默认0，终端默认1
     * @param getType 1:直播；2:回放，默认1
     * @param reload false:标识在缓存节目单时间不是当天时间时，重新修改策略为网络查询最新数据；ture:不重新查询，防止今天查询的当天节目单还是昨天的节目单日期，导致死循环
     */
    public List<WasuEditChRelated> queryAllTodayProgram(Context context, LiveCacheStrategy strategy, String type, String getType, String isZip, boolean reload){
        Uri uri = createUri(PATH_WASU_SDK_IPLIVE_PROGRAM);
        String[] param = new String[]{createStrategy(strategy), "", type, getType, "", "", "", "", "", isZip};
        WasuEditInfor wasuEditInfor =  createRequest(context, uri, param, RESULT_WASU_SDK_IPLIVE, WasuEditInfor.class);
        if (wasuEditInfor == null || wasuEditInfor.getChList() == null){
            return new ArrayList<>();
        }
        try {
            List<WasuEditChRelated> wasuEditChRelatedList = wasuEditInfor.getChList();
            if (wasuEditChRelatedList.size() <= 0){
                return new ArrayList<>();
            }
            List<WasuEdit> wasuEditList = wasuEditChRelatedList.get(0).getEventList();
            if (wasuEditList == null || wasuEditList.size() == 0){
                return wasuEditChRelatedList;
            }
            String todayDate = TimeUtil.getDate();
            String programDate = wasuEditList.get(0).getStartTime().split(" ")[0];
            Log.e(TAG, "queryAllTodayProgram, todayDate:"+todayDate+"; programDate:"+programDate+"; reload:"+reload);
            if (!reload && !todayDate.equals(programDate) && NetworkUtils.isConnected()){
                return queryAllTodayProgram(context, LiveCacheStrategy.NETWORK, type, getType, "1", true);
            }
        }catch (Exception e){ e.printStackTrace(); }
        return wasuEditInfor.getChList();
    }

    /**
     * 查询单个频道节目单列表
     */
    public WasuEditInfor queryProgramList(Context context, LiveCacheStrategy strategy, String type, String getType, String channelId){
        return queryProgramList(context, strategy, null, type, getType, "", "", channelId, "", "", "1");
    }
    public WasuEditInfor queryProgramList(Context context, LiveCacheStrategy strategy, String type, String getType, String channelId, String isZip){
        return queryProgramList(context, strategy, null, type, getType, "", "", channelId, "", "", isZip);
    }
    public WasuEditInfor queryProgramList(Context context, LiveCacheStrategy strategy, String type, String getType, String bId, String channelId, String isZip){
        return queryProgramList(context, strategy, null, type, getType, "", bId, channelId, "", "", isZip);
    }
    public WasuEditInfor queryProgramList(Context context, LiveCacheStrategy strategy, String type, String getType, String bIds, String bId, String channelId, String beginDate, String endDate){
        return queryProgramList(context, strategy, null, type, getType, bIds, bId, channelId, beginDate, endDate, "1");
    }
    public WasuEditInfor queryProgramList(Context context, LiveCacheStrategy strategy, String type, String getType, String bIds, String bId, String channelId, String beginDate, String endDate, String isZip){
        return queryProgramList(context, strategy, null, type, getType, bIds, bId, channelId, beginDate, endDate, isZip);
    }
    public WasuEditInfor queryProgramListKanBa(Context context, String type, String bId, String channelId){
        return queryProgramList(context, LiveCacheStrategy.ONLY_NETWORK, SYSTEM_CATEGORY_4K_IPDVB_KANBA, type, "2", "", bId, channelId, "", "", "1");
    }
    public WasuEditInfor queryProgramListKanBa(Context context, String type, String bId, String channelId, String isZip){
        return queryProgramList(context, LiveCacheStrategy.ONLY_NETWORK, SYSTEM_CATEGORY_4K_IPDVB_KANBA, type, "2", "", bId, channelId, "", "", isZip);
    }
    public WasuEditInfor queryProgramListKanBa(Context context, String type, String bId, String channelId, String startTime, String endTime, String isZip){
        return queryProgramList(context, LiveCacheStrategy.ONLY_NETWORK, SYSTEM_CATEGORY_4K_IPDVB_KANBA, type, "2", "", bId, channelId, startTime, endTime, isZip);
    }
    public WasuEditInfor queryProgramListHuiFang(Context context, String type, String bId, String channelId){
        return queryProgramList(context, LiveCacheStrategy.ONLY_NETWORK, SYSTEM_CATEGORY_4K_IPDVB_HUIFANG, type, "2", "", bId, channelId, "", "", "1");
    }
    public WasuEditInfor queryProgramListHuiFang(Context context, String type, String bId, String channelId, String isZip){
        return queryProgramList(context, LiveCacheStrategy.ONLY_NETWORK, SYSTEM_CATEGORY_4K_IPDVB_HUIFANG, type, "2", "", bId, channelId, "", "", isZip);
    }
    public WasuEditInfor queryProgramListQiuSuo(Context context, String type, String bId, String channelId){
        return queryProgramList(context, LiveCacheStrategy.ONLY_NETWORK, SYSTEM_CATEGORY_4K_IPDVB_QIUSUO, type, "2", "", bId, channelId, "", "", "1");
    }
    public WasuEditInfor queryProgramListQiuSuo(Context context, String type, String bId, String channelId, String isZip){
        return queryProgramList(context, LiveCacheStrategy.ONLY_NETWORK, SYSTEM_CATEGORY_4K_IPDVB_QIUSUO, type, "2", "", bId, channelId, "", "", isZip);
    }
    public WasuEditInfor queryProgramList(Context context, LiveCacheStrategy strategy, String category, String type, String getType, String bIds, String bId, String channelId, String beginDate, String endDate, String isZip){
        Uri uri = createUri(PATH_WASU_SDK_IPLIVE_PROGRAM);
        String[] param = new String[]{createStrategy(strategy), category, type, getType, bIds, bId, channelId, beginDate, endDate, isZip};
        WasuEditInfor wasuEditInfor = createRequest(context, uri, param, RESULT_WASU_SDK_IPLIVE, WasuEditInfor.class);
        if (wasuEditInfor == null || wasuEditInfor.getChList() == null){
            return new WasuEditInfor();
        }
        List<WasuEditChRelated> wasuEditChRelatedList = wasuEditInfor.getChList();
        if (wasuEditChRelatedList.size() == 0){
            return wasuEditInfor;
        }
        List<WasuEdit> wasuEditList = wasuEditChRelatedList.get(0).getEventList();
        if (wasuEditList == null || wasuEditList.size() <= 2){
            return wasuEditInfor;
        }
        swDesignativeChannelFilterProgram(wasuEditInfor, channelId, category);
        // DVB 的直播，做节目单【昨天】【今天】【明天】showDate 设置
        if (!AppCheckUtils.isIpTVType() && (TextUtils.isEmpty(category) || SYSTEM_CATEGORY_4K_IPDVB_LIVE.equals(category))){
            Log.v(TAG, "queryProgramList, dvb live player, reset show start date");
            try {
                // 昨天
                Date yesterday = getDataYesterday();
                // 今天
                Date today = getDateToday();
                // 明天
                Date tomorrow = getDateTomorrow();
                for (WasuEdit wasuEdit: wasuEditList){
                    resetProgramShowData(wasuEdit, yesterday, today, tomorrow);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
            return wasuEditInfor;
        }
        // IPTV的
        else {
            Log.v(TAG, "queryProgramList, iptv live player, sort by start time");
            return (("2".equals(type) || "6".equals(type)) && !SYSTEM_CATEGORY_4K_IPDVB_HUIFANG.equals(category)) ? sortProgram(wasuEditInfor) : wasuEditInfor;
        }
    }

    /**
     * 省网针对配置的频道，过滤节目单
     * 只有部分业务数据管理系统配置的频道，才有14天节目单，否则其他频道，手动过滤当前天往前推7天，往后不做处理，全部累计
     */
    private void swDesignativeChannelFilterProgram(WasuEditInfor wasuEditInfor, String channelId, String category){
        if (wasuEditInfor == null || wasuEditInfor.getChList() == null || wasuEditInfor.getChList().size() <= 0){
            return;
        }
        List<WasuEdit> wasuEditList = wasuEditInfor.getChList().get(0).getEventList();
        if (wasuEditList == null || wasuEditList.size() <= 0){
            return;
        }
        // 过滤从当天算，该天数之前的节目单
        int programReduceDays = 14;
        if (Config.isHz()){
            if (!AppCheckUtils.isIpTVType() && (TextUtils.isEmpty(category) || SYSTEM_CATEGORY_4K_IPDVB_LIVE.equals(category))){
                filterProgram(wasuEditList, programReduceDays);
            }
            return;
        }
        if (TextUtils.isEmpty(channelId)){
            return;
        }
        if (context == null){
            context = UILApplication.getInstance().getApplication().getApplicationContext();
        }
        int reduceDays = 7;
        try {
            String spSwChannelIds = SharedPreferenceHelper.getInstance(context, AppConstant.wasu_loader).loadString("channelId");
            String spReduceDays = SharedPreferenceHelper.getInstance(context, AppConstant.wasu_loader).loadString("swChannelReduceDays");
            Log.v(TAG, "swDesignativeChannelFilterProgram, spSwChannelIds:"+spSwChannelIds+"; spReduceDays:"+spReduceDays);
            if (!TextUtils.isEmpty(spReduceDays)){
                if (p.matcher(spReduceDays).matches()){
                    reduceDays = Integer.parseInt(spReduceDays);
                }
            }
            if (TextUtils.isEmpty(spSwChannelIds)){
                String result = getDic("4k-launcher", "channelId", "sw14ChannelInfo");
                Log.v(TAG, "swDesignativeChannelFilterProgram, query sw14ChannelInfo channelId dic result:"+result);
                if (TextUtils.isEmpty(result)){
                    Gson gson = new Gson();
                    DicList dicList = gson.fromJson(result, DicList.class);
                    if (dicList != null && dicList.getDicInfo() != null && dicList.getDicInfo().size() > 0){
                        DicInfo dicInfo = dicList.getDicInfo().get(0);
                        spSwChannelIds = dicInfo.getDictValue();
                        if (p.matcher(dicInfo.getRemark()).matches()){
                            reduceDays = Integer.parseInt(dicInfo.getRemark());
                        }
                        if (!TextUtils.isEmpty(spSwChannelIds)){
                            SharedPreferenceHelper.getInstance(context, AppConstant.wasu_loader).save("channelId", spSwChannelIds);
                        }
                    }
                }
            }
            Log.v(TAG, "swDesignativeChannelFilterProgram, start program size:"+wasuEditList.size()+"; channelId:"+channelId+"; reduceDays:"+reduceDays);
            if (TextUtils.isEmpty(spSwChannelIds)){
                return;
            }
            // 配置的频道信息不包含查询的频道，省网下只回调过去7天内节目单，否则节目单不做修改
            if (spSwChannelIds.contains(channelId)){
                if (!AppCheckUtils.isIpTVType() && (TextUtils.isEmpty(category) || SYSTEM_CATEGORY_4K_IPDVB_LIVE.equals(category))){
                    filterProgram(wasuEditList, programReduceDays);
                }
            }else {
                if (reduceDays < 2){ reduceDays = 7; }
                if (reduceDays > programReduceDays) { reduceDays = programReduceDays; }
                filterProgram(wasuEditList, reduceDays);
            }
            Log.v(TAG, "swDesignativeChannelFilterProgram, end program size:"+wasuEditList.size());
            wasuEditInfor.getChList().get(0).setEventList(wasuEditList);
        }catch (Exception e){
            Log.e(TAG, "swDesignativeChannelFilterProgram, query tvos project channelId error:"+e);
        }
    }

    /**
     * 按天过滤ipepg直播，过去节目单，入参 days 作用就是，以当天为界限，过滤掉过去 days 之外的节目单，未来的不处理
     * 例如：今天是10号，接口返回,5,6,7,8,9,10,11,12，days=3，过滤后的结果是，8,9,10,11,12
     */
    private void filterProgram(List<WasuEdit> wasuEditList, int days){
        Calendar calendar = Calendar.getInstance(Locale.CHINA);
        calendar.set(Calendar.DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH) - days + 1);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        long sevenDayAgoTime = calendar.getTime().getTime();
        Log.v(TAG, "queryProgramList, 开始过滤过去7天外的节目单, sevenDayAgoTime:"+TimeUtil.getStringFromLong(sevenDayAgoTime)+"; sevenDayAgoTime:"+sevenDayAgoTime+"; reduceDays:"+days);
        Iterator<WasuEdit> iterator = wasuEditList.iterator();
        while (iterator.hasNext()){
            WasuEdit wasuEdit = iterator.next();
            if (wasuEdit.getStartTimestamp() < sevenDayAgoTime){
                iterator.remove();
            }
        }
    }

    /**
     * 对type=2类型，单个频道所有天数节目单，每天的节目单，按照时间升序排序
     */
    private WasuEditInfor sortProgram(WasuEditInfor wasuEditInfor){
        if (wasuEditInfor == null || wasuEditInfor.getChList() == null){
            return wasuEditInfor;
        }
        List<WasuEditChRelated> wasuEditChRelatedList = wasuEditInfor.getChList();
        if (wasuEditChRelatedList == null || wasuEditChRelatedList.size() == 0){
            return wasuEditInfor;
        }
        try {
            List<WasuEdit> wasuEditList = wasuEditChRelatedList.get(0).getEventList();
            if (wasuEditList == null || wasuEditList.size() <= 2){
                return wasuEditInfor;
            }
            String start1 = wasuEditList.get(wasuEditList.size() - 2).getStartTime();
            String start2 = wasuEditList.get(wasuEditList.size() - 1).getStartTime();
            Log.v(TAG, "sortProgram, start1:"+start1+"; start2:"+start2);
            if (start1.compareTo(start2) <= 0){ return wasuEditInfor; }
            wasuEditInfor.getChList().get(0).setEventList(sortProgram(wasuEditList));
        }catch (Exception e){
            Log.e(TAG, "sortProgram, error:"+e);
        }
        return wasuEditInfor;
    }

    /**
     * 对type=2类型，单个频道所有天数节目单，每天的节目单，按照时间升序排序
     */
    private List<WasuEdit> sortProgram(List<WasuEdit> list){
        List<WasuEdit> resultList = new ArrayList<>(list.size());
        String data = "";
        List<WasuEdit> resultData = new ArrayList<>();
        for (int i = 0; i < list.size(); i++){
            String time = list.get(i).getStartTime().split(" ")[0];
            if (data.isEmpty()){ data = time; }
            if (!time.equals(data)){
                resultData.clear();
                resultData.addAll(list.subList(resultList.size(), i));
                sort(resultData);
                resultList.addAll(resultData);
                data = time;
            }
        }
        resultData.clear();
        resultData.addAll(list.subList(resultList.size(), list.size()));
        sort(resultData);
        resultList.addAll(resultData);
        return resultList;
    }

    private void sort(List<WasuEdit> list){
        Collections.sort(list, (o1, o2) -> o1.getStartTime().compareTo(o2.getStartTime()));
    }

    /**
     * 重新设置节目单显示的时间，将几月几日，在三天内的，改为昨天今天明天
     * 只修改IPEPG接口数据
     */
    private void resetProgramShowData(WasuEdit wasuEdit, Date yesterday, Date today, Date tomorrow) throws ParseException {
        String startData = wasuEdit.getStartTime();
        if (TextUtils.isEmpty(startData)){
            return;
        }
        String[] dataArray = startData.split(" ");
        if (dataArray.length <= 1){
            return;
        }
        if (TextUtils.isEmpty(wasuEdit.getShowStartTime())){
            String time = dataArray[1];
            String[] t = time.split(":");
            if (t.length > 1){
                wasuEdit.setShowStartTime(t[0] + ":" + t[1]);
            }else {
                wasuEdit.setShowStartTime(time);
            }
        }

        Date data = format.parse(dataArray[0]);
        if (yesterday.compareTo(data) == 0){
            wasuEdit.setShowStartDate("昨天");
        }else if (today.compareTo(data) == 0){
            wasuEdit.setShowStartDate("今天");
        }else if (tomorrow.compareTo(data) == 0){
            wasuEdit.setShowStartDate("明天");
        }else {
            if (wasuEdit.getShowStartDate() == null && data != null){
                wasuEdit.setShowStartDate(format2.format(data));
            }
        }
    }

    /**
     * 查询某个频道是否授权，仅在DVB模式直播使用，用于高标清替换是否支持的条件其一
     * @param context 上下文
     * @param wasuChInfor 频道信息
     * @return true:授权，false:未授权
     */
    public boolean queryChannelPurchased(Context context, WasuChInfor wasuChInfor){
        if (context == null){
            Log.e(TAG, "queryChannelPurchased, context can not be null");
            return false;
        }
        if (context instanceof Activity && (((Activity) context).isFinishing() || ((Activity) context).isDestroyed())){
            Log.e(TAG, "queryChannelPurchased, context is already destroy");
            return false;
        }
        if (wasuChInfor == null || wasuChInfor.getDvbLive() == null || TextUtils.isEmpty(wasuChInfor.getDvbLive().getCapId())){
            Log.e(TAG, "queryChannelPurchased, wasuChInfor or channelId can not be null");
            return false;
        }
        try {
            Uri uri = createUri(PATH_WASU_SDK_IPLIVE_CHANNEL_PURCHASED);
            String capId = wasuChInfor.getDvbLive().getCapId();
            String result = createRequest(context, uri, new String[]{wasuChInfor.getChId(), capId, "zhibo"}, RESULT_WASU_SDK_IPLIVE);
            Log.e(TAG, "queryChannelPurchased, query result:"+result);
            return Boolean.parseBoolean(result);
        }catch (Exception e){
            Log.e(TAG, "queryChannelPurchased, query result error:"+e);
            return false;
        }
    }

    /**
     * 创建一个请求
     * @param uri 地址
     * @param param 参数
     * @return 请求结果
     */
    private String createRequest(Context context, Uri uri, String[] param, String resultPath){
        if (context == null){
            context = UILApplication.getInstance().getApplication().getApplicationContext();
        }
        try(Cursor cursor = context.getContentResolver().query(uri, param, null, null, null)) {
            if (cursor == null || !cursor.moveToNext()){
                Log.e(TAG, "createRequest, query cursor is null or not next");
                return null;
            }
            int index  = cursor.getColumnIndex(resultPath);
            if (index < 0){
                Log.e(TAG, "createRequest, query cursor column index:"+index);
                return null;
            }
            return cursor.getString(index);
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 创建一个请求
     * @param uri 地址
     * @param param 参数
     * @param bean 转换类型
     * @return 请求结果
     */
    private <T> T createRequest(Context context, Uri uri, String[] param, String resultPath, Class<T> bean){
        if (context == null){
            context = UILApplication.getInstance().getApplication().getApplicationContext();
        }
        try(Cursor cursor = context.getContentResolver().query(uri, param, null, null, null)) {
            if (cursor == null || !cursor.moveToNext()){
                Log.e(TAG, "createRequest, query cursor is null or not next");
                return null;
            }
            int index  = cursor.getColumnIndex(resultPath);
            if (index < 0){
                Log.e(TAG, "createRequest, query cursor column index:"+index);
                return null;
            }
            String result = cursor.getString(index);
            if (TextUtils.isEmpty(result)){
                Log.e(TAG, "createRequest, query result is null");
                return null;
            }
            Gson gson = new Gson();
            return gson.fromJson(result, bean);
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根据策略获得判断的String值，因为cp只能传个String过去
     * @see com.wasu.sdk_ott.http.live.IpLiveCommonKt 具体对着这里
     * @return 策略值
     */
    private String createStrategy(LiveCacheStrategy strategy){
        String s = "0";
        switch (strategy){
            case ONLY_NETWORK:
                s = "0";
                break;
            case NETWORK:
                s = "1";
                break;
            case FIRST_NETWORK:
                s = "3";
                break;
            case ONLY_CACHE:
                s = "2";
                break;
            case FIRST_CACHE:
                s = "4";
                break;
            case FIRST_CACHE_TIMEOUT:
                s = "5";
                break;
            case CACHE_NETWORK:
                s = "6";
                break;
            case CACHE_REFRESH_CACHE:
                s = "7";
                break;
            default:
        }
        return s;
    }

    /**
     * 昨天日期，不含时间
     */
    private Date getDataYesterday() throws ParseException {
        // 昨天
        Calendar calendar1 = Calendar.getInstance();
        calendar1.set(Calendar.DAY_OF_MONTH, calendar1.get(Calendar.DAY_OF_MONTH) - 1);
        return format.parse(format.format(calendar1.getTime()));
    }

    /**
     * 今天日期，不含时间
     */
    private Date getDateToday() throws ParseException {
        return format.parse(format.format(Calendar.getInstance().getTime()));
    }

    /**
     * 昨天日期，不含时间
     */
    private Date getDateTomorrow() throws ParseException {
        // 明天
        Calendar calendar3 = Calendar.getInstance();
        calendar3.set(Calendar.DAY_OF_MONTH, calendar3.get(Calendar.DAY_OF_MONTH) + 1);
        return format.parse(format.format(calendar3.getTime()));
    }

}
